package com.handpay.zztong.hp.main.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.db.ormlite.DataBaseComponentModel;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.main.model.bannerschannel.BannersByChannelBean;
import com.handpay.zztong.hp.main.model.bannerschannel.BannersChannelModel;
import com.handpay.zztong.hp.main.model.component.ComponentMappingItemBean;
import com.handpay.zztong.hp.main.widget.icon.IconBaseAdapter;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.NewsInfo;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.FunctionInfo;
import com.handpay.zztong.hp.main.widget.icon.IconBaseOnItemClickListener;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.AdGallery;
import com.handpay.zztong.hp.ui.AdGallery.OnAdItemClickListener;
import com.handpay.zztong.hp.ui.AdGalleryHelper;
import com.handpay.zztong.hp.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;


@SuppressLint("NewApi")
public class HomeFragment extends BaseFragment implements OnAdItemClickListener, ApiNoticeListener {
    private static final String TAG = "HomeFragment";

    private ArrayList<String> mData = null;
    private NewsInfo[] ads = new NewsInfo[]{};
    private AdGalleryHelper adGalleryHelper = null;
    private AdGallery adGallery = null;
    private GridView myGridView = null;
    protected IconBaseAdapter mIconBaseAdapter;
    protected RelativeLayout container;
    private IconBaseOnItemClickListener mIconBaseOnItemClickListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTranslucentForImageViewInFragment(mainActivity, 0, null);

//        mBannersChannelModel = new BannersChannelModel();
//        Resources res = mActivity.getResources();
//        maps = FunctionInfo.getFunctionInfos();
//        data = new ArrayList<FunctionInfo.FunctionType>();
//        data.add(FunctionInfo.FunctionType.collectmoney);
//        boolean isShowScannerCodePay = res.getBoolean(R.bool.isShowScannerCodePay);
//        if (isShowScannerCodePay) {
//            //扫码收款
//
//            data.add(FunctionInfo.FunctionType.ScannerCodePay);
//        }
//        //代还信用卡
//
//        data.add(FunctionInfo.FunctionType.LoanCreditCard);
//        //银联转账
//
//        data.add(FunctionInfo.FunctionType.Loan);
//
//        //分销系统
//
//        data.add(FunctionInfo.FunctionType.DistributionSystem);
//        //捷安借贷
//
//        data.add(FunctionInfo.FunctionType.JieAn);
//        //证券开户
//
//        data.add(FunctionInfo.FunctionType.OpenAcountAOP);
//        //话费充值
////        data.add(FunctionInfo.FUNCTIONID[4]);
//        boolean isShowQQConsultation = res.getBoolean(R.bool.isShowQQConsultation);
//        if (isShowQQConsultation) {
//            data.add(FunctionInfo.FunctionType.QQConsultation);
//        }
//        data.add(FunctionInfo.FunctionType.AllFunction);

        mData = new ArrayList<String>();

        doShowComponentItem();


        doGetBannersByChannel();
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != mViewGroup) {
            ViewGroup parent = (ViewGroup) mViewGroup.getParent();
            if (null != parent) {
                parent.removeView(mViewGroup);
            }
        } else {
            mViewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false);
            initView();
        }
        StatusBarUtil.setTranslucentForImageViewInFragment(mainActivity, 0, null);
        return mViewGroup;
    }

    private void initView() {
        container = (RelativeLayout) mViewGroup.findViewById(R.id.banner_news_container);
        myGridView = (GridView) mViewGroup.findViewById(R.id.homeGridView);
        mIconBaseAdapter = new IconBaseAdapter(mainActivity);
        myGridView.setAdapter(mIconBaseAdapter);
        mIconBaseAdapter.setData(mData);
        mIconBaseOnItemClickListener = new IconBaseOnItemClickListener(mainActivity);
        myGridView.setOnItemClickListener(mIconBaseOnItemClickListener);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // loadTestBannerData();
    }

    @Override
    public void onResume() {
        super.onResume();
        MainActivity.currFragTag = ZZTConstant.FRAGMENT_FLAG_HOME;
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
        super.onDestroy();
    }


//    @Override
//    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, OnClickListener on) {
//        if (action.equals(ZZTongActivity.Do_GetBannersByChannel)) {
//            BannersByChannelBean bean = (BannersByChannelBean)resp;
////            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
////            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//            HPLog.i(HPLog.LFP_TAG, "have banner datas");
//            // 测试数据
//            if (bean == null) {
//                NewsInfo n1 = new NewsInfo();
//                ads = new NewsInfo[1];
//                n1.setCoverUrl("https://www.handmart.cn/web/MPOSBanners/BannerResources/newversionintroduction.png");
//                n1.setBannerName("海通证劵");
//                n1.setContentUrl("https://www.handmart.cn/web/MPOSBanners/LinkURLResources/newversionintroductiondetail.png");
//                n1.setBannerLinkType("1");
//                ads[0] = n1;
//            } else {
//                String items =  bean.getItems();
//                ads = NewsInfo.getNewListsArray(bean, items);
//            }
//            if (ads != null && ads.length > 0) {
//                adGalleryHelper = new AdGalleryHelper(getActivity(), ads, 5000, ads.length > 1 ? true : false, width, height);
//                container.addView(adGalleryHelper.getLayout());
//                adGallery = adGalleryHelper.getAdGallery();
//                // 轮换广告的点击事件绑定
//                adGallery.setAdOnItemClickListener(this);
//            } else {
//                HPLog.i(HPLog.LFP_TAG, "ads==null");
//            }
//        }
//        return false;
//    }


    @Override
    public String getFragmetTitle() {
        return ZZTConstant.FRAGMENT_FLAG_HOME;
    }

    @Override
    public ActionBar getFragmentActionBar() {
        super.getFragmentActionBar();
        return new ActionBar(getFragmetTitle());
    }

    private void doGetBannersByChannel() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("showTab", "01");
        new BannersChannelModel().doBannersByChannelPost(mainActivity, params, new BusinessEngineListener<BannersByChannelBean>() {
            @Override
            public void callbackBusinessResponse(BannersByChannelBean bean) {
                if (bean == null) {
                    NewsInfo n1 = new NewsInfo();
                    ads = new NewsInfo[1];
                    n1.setCoverUrl("https://www.handmart.cn/web/MPOSBanners/BannerResources/newversionintroduction.png");
                    n1.setBannerName("海通证劵");
                    n1.setContentUrl("https://www.handmart.cn/web/MPOSBanners/LinkURLResources/newversionintroductiondetail.png");
                    n1.setBannerLinkType("1");
                    ads[0] = n1;
                } else {
                    String items = bean.getItems();
                    ads = NewsInfo.getNewListsArray(bean, items);
                }
                if (ads != null && ads.length > 0) {
                    adGalleryHelper = new AdGalleryHelper(getActivity(), ads, 5000, ads.length > 1, width, height);
                    container.addView(adGalleryHelper.getLayout());
                    adGallery = adGalleryHelper.getAdGallery();
                    // 轮换广告的点击事件绑定
                    adGallery.setAdOnItemClickListener(HomeFragment.this);
                } else {
                    HPLog.i(HPLog.LFP_TAG, "ads==null");
                }
            }
        });
    }

    @Override
    public void setItemClick(int position) {
        if (ads != null) {
            NewsInfo info = ads[position];
            try {
                if (NewsInfo.InternalHTML.equals(info.getBannerLinkType()) || NewsInfo.ExternalHTML.equals(info.getBannerLinkType())) {
                    Intent intent1 = new Intent(getActivity(), ShowHtmlActivity.class);
                    intent1.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, info.getBannerName() == null ? "" : info.getBannerName());
                    intent1.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, info.getContentUrl());
                    getActivity().startActivity(intent1);
                } else if (NewsInfo.InternalAPP.equals(info.getBannerLinkType())) {
                    mIconBaseOnItemClickListener.gridViewItemOnclick(info.getContentUrl());
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
        HPLog.i(HPLog.YL_TAG, "HomeFragment onNotifyNotice Action:" + action + " Bundle:" + bundle);
        if (action == REFRESH_COMPONENT_ACTION) {
            doShowComponentItem();
            mIconBaseAdapter.setData(mData);
        }
    }

    private void doShowComponentItem() {
        try {
            mData.clear();
            DataBaseComponentModel dbModel = null;
            dbModel = new DataBaseComponentModel(mActivity);
            List<ComponentMappingItemBean> list = dbModel.queryComponentMappingByShowArea("1");
            for (ComponentMappingItemBean bean : list) {
                mData.add(bean.getItemCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            mData.clear();
            mData.add(FunctionInfo.COLLECT_MONEY_CODE);
            mData.add(FunctionInfo.SCAN_PAYMENT_CODE);
            mData.add(FunctionInfo.MONG_HOO_CODE);
            mData.add(FunctionInfo.HONG_SHOP_CODE);
            mData.add(FunctionInfo.QQ_IM_CODE);
            mData.add(FunctionInfo.GATHER_APP_CODE);
        }
    }


    @Override
    public int[] getNoticeAction() {
        int actions[] = {REFRESH_COMPONENT_ACTION};
        return actions;
    }
}
